package com.future.hedongjun.mall.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.FullyLinearLayoutManager;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.common.PriceHelper;
import com.future.hedongjun.mall.adapter.OrderDetailAdapter;
import com.future.hedongjun.mall.bean.GoodsDetail;
import com.future.hedongjun.mall.bean.OrderDetail;
import com.future.hedongjun.mine.bean.DeliveryAddressBean;
import com.future.hedongjun.mine.bean.response.CouponListResponse;
import com.future.hedongjun.mine.order.PayActivity;
import com.future.hedongjun.mine.ui.DeliveryAddressActivity;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConfirmOrderActivity extends BaseActivity {

    public static final String ORDER_NO_BUNDLE_KEY = "order_no";
    public static final int CHOOSE_ADDRESS = 0X321;
    public static final int CHOOSE_COUPON = 0x123;

    @BindView(R.id.tv_address_mode)
    TextView tvAddressMode;
    @BindView(R.id.layout_empty_shipping_address)
    RelativeLayout layoutEmptyShippingAddress;
    @BindView(R.id.tv_custom_name)
    TextView tvCustomName;
    @BindView(R.id.tv_custom_phone)
    TextView tvCustomPhone;
    @BindView(R.id.tv_custom_address)
    TextView tvCustomAddress;
    @BindView(R.id.layout_shipping_address)
    RelativeLayout layoutShippingAddress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R.id.layout_coupon)
    FrameLayout layoutCoupon;
    @BindView(R.id.tv_price_commodity)
    TextView tvPriceCommodity;
    @BindView(R.id.layout_price_commodity)
    FrameLayout layoutPriceCommodity;
    @BindView(R.id.tv_coupon_price)
    TextView tvCouponPrice;
    @BindView(R.id.tv_should_pay)
    TextView tvShouldPay;
    @BindView(R.id.tv_should_pay_price)
    TextView tvShouldPayPrice;
    @BindView(R.id.btn_pay)
    Button btnPay;
    private String coupon_id;
    private DeliveryAddressBean addressBean;
    private ArrayList<GoodsDetail> goodsData;
    private ArrayList<Integer> nums;
    private DeliveryAddressBean selectAddress;
    private double totalPrice = 0;
    private double couponPrice = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        ButterKnife.bind(this);

        setTitle("确认订单");


        recyclerView.setLayoutManager(new FullyLinearLayoutManager(this));
        recyclerView.setNestedScrollingEnabled(false);
        ArrayList<OrderDetail.GoodsBean> data = new ArrayList<>();
        for (int i = 0; i < goodsData.size(); i++) {
            OrderDetail.GoodsBean bean = new OrderDetail.GoodsBean();
            GoodsDetail detail = goodsData.get(i);
            bean.imgUrl = detail.getImage();
            bean.count = nums.get(i);
            bean.title = detail.getGoods_name();
//            bean.price = detail.goodsPrice;
            totalPrice += bean.price * bean.count;
            data.add(bean);
        }
        recyclerView.setAdapter(new OrderDetailAdapter(data));

        refreshAddress(null);
        getDefaultAddress();
        getCanUseCouponCount();
        refreshPrice();
    }

    private void getCanUseCouponCount() {
        new HttpRequest<CouponListResponse>()
                .with(this)
                .setApiCode("_canusediscount_001")
                .addParam("userToken", MyApp.getInstance().getUserToken())
                .addParam("amount", "" + totalPrice)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        tvCoupon.setText(((CouponListResponse) response).data.size() + "张可用");
                    }
                }).start(new CouponListResponse());
    }

    private void refreshPrice() {
        tvPriceCommodity.setText(PriceHelper.priceFormat(totalPrice));
        tvCouponPrice.setText("- " + PriceHelper.priceFormat(couponPrice));
        tvShouldPayPrice.setText(PriceHelper.priceFormat(totalPrice - couponPrice));
    }

    private void getDefaultAddress() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode("_myoldaddress_001")
                .addParam("userToken", MyApp.getInstance().getUserToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        DeliveryAddressBean bean = new Gson().fromJson(response.data, DeliveryAddressBean.class);
                        refreshAddress(bean);
                    }
                }).start(new DefaultResponse());
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        goodsData = (ArrayList<GoodsDetail>) extras.getSerializable("data");
        nums = (ArrayList<Integer>) extras.getSerializable("nums");
    }

    public static void open(Context context, GoodsDetail detail, int num) {
        Intent intent = new Intent(context, ConfirmOrderActivity.class);
        ArrayList<GoodsDetail> data = new ArrayList<>();
        data.add(detail);
        ArrayList<Integer> nums = new ArrayList<>();
        nums.add(num);
        intent.putExtra("data", data);
        intent.putExtra("nums", nums);
        context.startActivity(intent);
    }

    public static void open(Context context, ArrayList<GoodsDetail> details, ArrayList<Integer> nums) {
        if (details == null || nums == null || details.size() != nums.size()) {
            return;
        }
        Intent intent = new Intent(context, ConfirmOrderActivity.class);
        intent.putExtra("data", details);
        intent.putExtra("nums", nums);
        context.startActivity(intent);
    }


    @OnClick({R.id.layout_empty_shipping_address, R.id.layout_shipping_address, R.id.layout_coupon, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_empty_shipping_address:
            case R.id.layout_shipping_address:
                Bundle bundle = new Bundle();
                bundle.putString("type", "1");
                startActivityForResult(DeliveryAddressActivity.class, bundle, CHOOSE_ADDRESS);
                break;
            case R.id.layout_coupon:
                Bundle bundle1 = new Bundle();
                bundle1.putDouble("amount", totalPrice);
                startActivityForResult(CouponListActivity.class, bundle1, CHOOSE_COUPON);
                break;
            case R.id.btn_pay:
                pay();
                break;
        }
    }

    private void pay() {
        if (selectAddress == null) {
            toast("请先选择收货地址");
            return;
        }
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode("_addshopindent_001")
                .addParam("userToken", MyApp.getInstance().getUserToken())
                .addParam("real_id", "")//商品id 数量
                .addParam("discount_id", coupon_id)
                .addParam("address_id", selectAddress.getAddress_id())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        try {
                            String order_num = new JSONObject(response.data).optString("order_num");
                            PayActivity.openByShop(ConfirmOrderActivity.this, totalPrice - couponPrice, order_num);
                        } catch (JSONException e) {
                            toast("返回数据异常");
                        }
                    }
                }).start(new DefaultResponse());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == resultCode && requestCode == CHOOSE_ADDRESS) {
            Serializable address = data.getSerializableExtra("address");
            if (address instanceof DeliveryAddressBean) {
                addressBean = (DeliveryAddressBean) address;
                refreshAddress(addressBean);
            }
//            refreshAddress(data);
        } else if (requestCode == resultCode && requestCode == CHOOSE_COUPON) {
            Bundle extras1 = data.getExtras();
            couponPrice = extras1.getDouble("price", 0);
            coupon_id = extras1.getString("couponId", "");
            tvCoupon.setText("已使用1张");
            refreshPrice();
        }
    }

    private void refreshAddress(DeliveryAddressBean addressBean) {
        selectAddress = addressBean;
        if (addressBean == null) {
            layoutEmptyShippingAddress.setVisibility(View.VISIBLE);
            layoutShippingAddress.setVisibility(View.GONE);
        } else {
            layoutEmptyShippingAddress.setVisibility(View.GONE);
            layoutShippingAddress.setVisibility(View.VISIBLE);
            tvCustomName.setText(addressBean.getName());
            tvCustomPhone.setText(addressBean.getPhone());
            tvCustomAddress.setText(addressBean.getLocation());
        }
    }
}
